package itsm.isperp.module.service.app;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.commons.repository.BaseRepository;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.message.domain.MessageType;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppMessageSuccess;
import itsm.isperp.module.repository.app.AppMessageSuccessMapper;
import itsm.isperp.module.service.wechat.WechatChatService;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class AppMessageSuccessService extends BaseService<AppMessageSuccess> {

	@Autowired
	protected AppMessageSuccessMapper appMessageSuccessMapper;

	@Autowired
	WechatChatService wechathChatService;

	@Override
	public BaseRepository<AppMessageSuccess> getRepository() {
		return this.appMessageSuccessMapper;
	}

	public List<Map<String, Object>> findMyMessage(boolean isReaded, int row) {
		if (ContextHolder.isLogin()) {
			JqGridRequest request = new JqGridRequest();
			request.isPageable(false);
			request.setRows(row);
			request.addFilterRule("receiver_id", JqGridFilterRuleOp.eq,
					ContextHolder.getLoginUsername());
			request.addFilterRule("readed", JqGridFilterRuleOp.eq,
					isReaded ? "1" : "0");

			return this.appMessageSuccessMapper.findAllDetailByRequest(request);
		}
		return null;
	}

	public Map<String, Object> findMyMessageAllCount(String username) {
		Map<String, Object> map = new HashMap<>();
		Integer messageTotal = findMyMessageCount(username, false);
		map.put("messageTotal", messageTotal);

		JqGridFilter filter = new JqGridFilter();
		filter.addRule("relation_id", JqGridFilterRuleOp.isnull, "");
		Long wechatTotal = wechathChatService.findAllCount(filter);
		map.put("wechatTotal", wechatTotal);

		return map;
	}

	public Integer findMyMessageCount(String username, boolean isReaded) {

		return this.appMessageSuccessMapper.findMyMessageCount(username,
				isReaded);

	}

	public void markReadMessage(final String id) {
		AppMessageSuccess msg = new AppMessageSuccess();
		msg.setId(id);
		msg.setReaded(true);
		msg.setReadTime(new Timestamp(new Date().getTime()));
		HashSet<String> set = new HashSet<String>();
		set.add("readed");
		set.add("readTime");

		this.getRepository().dynamicSpecificUpdate(msg, set);

	}

	public void markReadMessage() {
		JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");

		jdbcTemplate
				.update("UPDATE app_message_success SET readed=1,read_time=now() WHERE RECEIVER_ID='"
						+ ContextHolder.getLoginUsername() + "'");
	}

	public List<AppMessageSuccess> findAllLeaveMessage(String sourceId) {
		JqGridRequest request = new JqGridRequest();
		request.isPageable(false);

		request.addFilterRule("message_type", JqGridFilterRuleOp.eq,
				MessageType.LEAVEMSG);
		request.addFilterRule("source_id", JqGridFilterRuleOp.eq, sourceId);
		request.setSort("create_date", Direction.ASC);

		return this.findAll(request);

	}

	public void saveLeaveMessage(IUser sender, boolean areFromCustomer,
			String sourceId, String title, String content) {
		AppMessageSuccess msg = new AppMessageSuccess();
		msg.setId(HibernateUUIDGenerator.generate());
		msg.setReaded(false);
		msg.setSender(sender.getUsername());
		msg.setSender(sender.getUsername());
		msg.setMessageLevel(1);
		msg.setCreator(sender.getUsername());
		msg.setCreatorName(sender.getFullname());
		msg.setCreateDate(new Timestamp(new Date().getTime()));
		msg.setModifier(sender.getUsername());
		msg.setModifierName(sender.getFullname());
		msg.setModifyDate(new Timestamp(new Date().getTime()));

		msg.setTitle(title);
		msg.setContent(content);
		msg.setAreFromCustomer(areFromCustomer);

		msg.setSourceId(sourceId);
		msg.setMessageType(MessageType.LEAVEMSG.toString());
		msg.setAreLeave(true);
		this.getRepository().save(msg);

	}

	public void readAllLeaveMessage(String sourceId, String username) {
		this.appMessageSuccessMapper.readAllLeaveMessage(sourceId, username,
				new Timestamp(new Date().getTime()));

	}

	/**
	 * 查询当前用户关联消息的sql条件
	 * 
	 * @return
	 */
	private static String getRelationCondition(boolean all) {

		String s = "  (message_type IN ('" + MessageType.LEAVEMSG + "','"
				+ MessageType.MSG + "')) ";

		if (!all) {
			s += " AND  receiver_id='" + ContextHolder.getLoginUsername() + "'";
		}

		return s;
	}

	public List<Map<String, Object>> findRelationCountsBySourceIds(
			String[] ids, boolean all) {
		return this.appMessageSuccessMapper.findCountsBySourceIds(ids,
				getRelationCondition(all) + " AND message_level=1");
	}

	public DataResponse<Map<String, Object>> findAllRelationBySourceId(
			JqGridRequest req, String sourceId, boolean all) {
		req.addFilterRule("source_id", JqGridFilterRuleOp.eq, sourceId);
		String condition = getRelationCondition(all);
		req.setSearchString(condition);

		return appMessageSuccessMapper.findAllDetailByRequest(req);
	}

}
